﻿using System.Configuration;
using System;

namespace YouDaoNotesCodes
{
    public class selfDefine1Section : ConfigurationSection
    {
        #region 自定义配置文件读取-方式1：Property
        [ConfigurationProperty("fileName", DefaultValue = "default.txt", IsRequired = true, IsKey = false)]
        //[StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
        public string FileName
        {
            get { return (string)this["fileName"]; }
            set { this["fileName"] = value; }
        }

        [ConfigurationProperty("maxUsers", DefaultValue = (long)10000, IsRequired = false)]
        //[LongValidator(MinValue = 1, MaxValue = 10000000, ExcludeRange = false)]
        public long MaxUsers
        {
            get { return (long)this["maxUsers"]; }
            set { this["maxUsers"] = value; }
        }

        [ConfigurationProperty("maxIdleTime", DefaultValue = "0:10:0", IsRequired = false)]
        //[TimeSpanValidator(MinValueString = "0:0:30", MaxValueString = "5:00:0", ExcludeRange = false)]
        public TimeSpan MaxIdleTime
        {
            get { return (TimeSpan)this["maxIdleTime"]; }
            set { this["maxIdleTime"] = value; }
        }

        #endregion

        //方式1调用
        public void getSectionByProperty()
        {
            selfDefine1Section se1 = (selfDefine1Section)System.Configuration.ConfigurationManager.GetSection("selfDefine1");
            Console.Write(se1.FileName);
            Console.ReadKey();
        }

        #region 自定义配置文件写入-方式1
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);//首先定义一个全局变量
        public void writeSectionByProperty()
        {
            selfDefine1Section se1config = config.GetSection("selfDefine1") as selfDefine1Section;
            se1config.FileName = "this is modify";
            se1config.MaxUsers = 1200;
            TimeSpan ts = new TimeSpan(10,2,4);
            se1config.MaxIdleTime = ts;
            config.Save();
        }
        #endregion
    }
}